package com.yuyou.tas.admin.service.impl;

import com.yuyou.tas.admin.mapper.CommJobMapper;
import com.yuyou.tas.admin.service.ICommJobService;
import com.yuyou.tas.admin.tool.MailUtil;
import com.yuyou.tas.service.api.admin.entity.CommJob;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.admin.CommJobEnums;
import com.yuyou.tas.util.tool.Sequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class CommJobServiceImpl implements ICommJobService{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());  
	
	@Autowired
	private CommJobMapper commJobMapper;
	
	@Value("${denfind.env}")
	private  String denfindEnv;
	
	
	
	@Override
	public int deleteByPrimaryKey(Long id) {
		return commJobMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(CommJob record) {
		Date now = new Date();
		record.setId(Sequence.getSequence().nextId());
		record.setCreateTime(now);
		record.setInitTime(now);
		record.setHasTime(0);
		record.setNeedRetry(CommJobEnums.needRetry.getByType(record.getType()));
		record.setMaxTime(CommJobEnums.maxTime.getByType(record.getType()));
		return commJobMapper.insert(record);
	}

	@Override
	public CommJob selectByPrimaryKey(Long id) {
		return commJobMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<CommJob> findLoadedJob(Long allotTempId){
		return commJobMapper.findLoadedJob(allotTempId);
	}
	
	@Override
	public int updateByPrimaryKeySelective(CommJob record) {
		return commJobMapper.updateByPrimaryKeySelective(record);
	}
	
	@Override
	public ResBoolSimpleInfo<String> updateLoadedJob(Long allotTempId){
		commJobMapper.updateLoadedJob(allotTempId);
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	@Override
	public ResBoolSimpleInfo<String> addJob(Long fId,Integer type,String tag){
		CommJob record=new CommJob();
		record.setfId(fId);
		record.setType(type);
		record.setTag(tag);
		record.setStatus(CommJobEnums.status.init.getValue());
		Date now = new Date();
		record.setCreateTime(now);
		record.setInitTime(now);

		record.setHasTime(0);
		record.setNeedRetry(CommJobEnums.needRetry.getByType(record.getType()));
		record.setMaxTime(CommJobEnums.maxTime.getByType(record.getType()));

		this.insert(record);
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public void insertJobs(List<CommJob> list) {
		list.forEach(commJob -> commJobMapper.insert(commJob));
	}

	@Override
	public ResBoolSimpleInfo<String> updateJobStatus(Long fId, Integer type,
			String tag, Integer status) {
		if(CommJobEnums.status.fail.getValue() == status){
			CommJob commJob = commJobMapper.selectByFId(fId,type,tag);
			if(commJob != null){
				if(commJob.getNeedRetry() == 1 && commJob.getHasTime() != commJob.getMaxTime()){//需要重试
					commJob.setStatus(CommJobEnums.status.init.getValue());
					commJob.setHasTime(commJob.getHasTime()+1);

					//计算下次运行时间（增加间隔时间）
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(new Date());
					calendar.add(Calendar.MINUTE,CommJobEnums.interval.getMaxByTimes(commJob.getHasTime()));
					commJob.setCreateTime(calendar.getTime());

					commJobMapper.updateByPrimaryKeySelective(commJob);
				}else {
					commJobMapper.updateJobStatus(fId, type, tag, status);
				}
			}
		}else {
			commJobMapper.updateJobStatus(fId, type, tag, status);
		}
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public List<CommJob> findAlarmCommJob(Date time) {
		return commJobMapper.findAlarmCommJob(time);
	}

	@Autowired
	private MailUtil mailUtil;
	
	@Override
	public void alarmCommJob() {
		
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE,-30);
        Date alarmTimeCondi=calendar.getTime();
        
        List<CommJob> cjList=this.findAlarmCommJob(alarmTimeCondi);
        Date now=new Date();
    	if(cjList.size()>0){
    		StringBuilder ids=new StringBuilder();
    		ids.append(denfindEnv+"\r\n");
        	for(CommJob c:cjList){
        		CommJob up=new CommJob();
        		up.setId(c.getId());
        		up.setAlarmTime(now);
        		this.updateByPrimaryKeySelective(up);
        		ids.append(c.getfId()+"|"+c.getType()+"|"+c.getTag()+"|"+c.getRemark()+"\r\n");
        	}
        	//发告警邮件
        	mailUtil.sendMonitorEmail("alarmCommJob",ids.toString());        	
    	}
        
        
        
	}
	
	

}